//
//  AppDelegate.m
//  DoctorProject
//
//  Created by zhibao on 2021/11/3.
//

#import "AppDelegate.h"
#import "WelcomeController.h"
#import "LNavigationViewController.h"
#import <StoreKit/StoreKit.h>
#import "FirstPayController.h"
#import "HomeController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
@interface AppDelegate ()<SKPaymentTransactionObserver>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UMConfigure initWithAppkey:@"64ed856b5488fe7b3afff956" channel:@"APP Store"];
    [MobClick setAutoPageEnabled:YES];
    [Helper getWANIP];
    
    /*
     * 初始化
     */
    
    [AMapServices sharedServices].apiKey =@"7bc255496360393791e2f3075cf1b2ef";
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"agreeStatus"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //更新用户授权高德SDK隐私协议状态. since 2.8.0
    [AMapLocationManager updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    [AMapLocationManager updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = UIColor.whiteColor;
    [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
        
    }];
    if(![IAPShare sharedHelper].iap) {
        
        NSSet* dataSet = [[NSSet alloc] initWithObjects:@"com.wuyuan.shuiyin.yongjiu",@"com.wuyuan.shuiyin.year",@"com.wuyuan.shuiyin.month", @"com.wuyuan.shuiyin.week", nil];
        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
    }
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
     {
        //DLog(@"response==%@",response.products);
    }];
    [IAPShare sharedHelper].iap.production = NO;
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    //[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    /*
     * 初始化
     */
    
    //导航
    [self setNavConfig];
    //初始化
    [self setTabbarController];
    
    [self.window makeKeyAndVisible];
    
    NSDate *oldTime =  [[NSUserDefaults standardUserDefaults]objectForKey:@"storeStarTime"];
    if (oldTime) {
        //利用NSCalendar比较日期的差异
        NSCalendar *calendar = [NSCalendar currentCalendar];
        
        NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
        //比较的结果是NSDateComponents类对象
        NSDateComponents *delta = [calendar components:unit fromDate:oldTime toDate:[NSDate date] options:0];
        BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:@"flag"];
        if (delta.day >= 7 && flag) {
            [self showStore];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"flag"];
        }
    }else{
        [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"storeStarTime"];
    }
    
    return YES;
}

-(void)showStore{
    if (@available(iOS 10.3, *)) {
        if([SKStoreReviewController respondsToSelector:@selector(requestReview)]) {// iOS 10.3 以上支持
            //防止键盘遮挡
            [[UIApplication sharedApplication].delegate.window endEditing:YES];
            [SKStoreReviewController requestReview];
        }else{
            NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"6446334006"];//替换为对应的APPID
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
        
    } else {
        NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"6468908434"];//替换为对应的APPID
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:^(BOOL success) {
            
        }];
    }
    [[NSUserDefaults standardUserDefaults]setObject:[NSDate date] forKey:@"storeStarTime"];
}

- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return NO;
}

- (void)setTabbarController {
    NSString *tempFirstStr = [[NSUserDefaults standardUserDefaults] valueForKey:WelcomeFlag];
    MYAPP.window.rootViewController = [UIViewController new];
    DLog(@"eeeee===%@",[UserInfoManager sharedManager].vip_expiry_date);
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2024-03-01 08:00:00"]) {
        [MYGlobal share].wechatFlag = 1;
    }
    
    if([MYGlobal share].wechatFlag == 1){
        HomeController *controller = [[HomeController alloc] init];
        LNavigationViewController *nav = [LNavigationViewController rootVC:controller];
        nav.gk_openScrollLeftPush = YES;
        nav.gk_openSystemNavHandle = YES;
        self.window.rootViewController = nav;
    }else{
        if (tempFirstStr.length > 4) {
            if([[UserInfoManager sharedManager] isVip]){
                HomeController *controller = [[HomeController alloc] init];
                LNavigationViewController *nav = [LNavigationViewController rootVC:controller];
                nav.gk_openScrollLeftPush = YES;
                nav.gk_openSystemNavHandle = YES;
                self.window.rootViewController = nav;
            }else{
                FirstPayController *controller = [[FirstPayController alloc] init];
                LNavigationViewController *nav = [LNavigationViewController rootVC:controller];
                nav.gk_openScrollLeftPush = YES;
                nav.gk_openSystemNavHandle = YES;
                self.window.rootViewController = nav;
            }
        }else{
            self.window.rootViewController = [WelcomeController new];
        }
    }
    
    [[HttpHelper sharedInstance] sendGet:@"api/system/state" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        DLog(@"state==%@",responseObject.data);
        [MYGlobal share].wechatFlag = [responseObject.data[@"data"][@"state"] intValue];
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}

- (void)setNavConfig {
    //    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // 配置导航栏属性
    [GKConfigure setupCustomConfigure:^(GKNavigationBarConfigure *configure) {
        //       configure.gk_translationX = 15;
        //       configure.gk_translationY = 20;
        configure.backgroundColor = MyColor(@"#000000");
        configure.titleFont = MY_SCALE_RegularFONT(18);
        configure.titleColor = MyColor(@"#000000");
        //       configure.gk_scaleX = 0.90;
        configure.backImage = [UIImage imageNamed:@"arrow_back"];
        //       configure.gk_scaleY = 0.92;
        configure.gk_navItemLeftSpace = 5.0f;
        configure.gk_navItemRightSpace = 5.0f;
    }];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = YES;
}

-(BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable restorableObjects))restorationHandler NS_AVAILABLE_IOS(8_0); {
    
    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application{
    
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return YES;
}


#pragma mark - 程序将要进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    DLog(@"程序将要进入前台");
}

- (void)paymentQueue:(nonnull SKPaymentQueue *)queue updatedTransactions:(nonnull NSArray<SKPaymentTransaction *> *)transactions {
    if(![UserInfoManager sharedManager].isLogin){
        return;
    }
    if(transactions.count > 0){
        SKPaymentTransaction *tran = transactions.lastObject;
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                [self verifyPurchaseWithPaymentTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                
                break;
            default:
                break;
        }
    }
}
- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction{
    //交易验证
    NSURL *recepitURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receipt = [NSData dataWithContentsOfURL:recepitURL];
    if(!receipt){
        return;
    }
    DLog(@"data==%@",[receipt base64EncodedStringWithOptions:0]);
    NSDictionary *paras =@{
        @"receipt":[receipt base64EncodedStringWithOptions:0],
        @"productId":transaction.payment.productIdentifier,
        @"transactionId":transaction.transactionIdentifier
    };
    [[HttpHelper sharedInstance] sendPost:@"api/pay/subscribe" parameters:paras success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        DLog(@"payfinish===%@",responseObject.data);
        if (responseObject.code == 1) {
            [[UserInfoManager sharedManager] getUserInfoData:^(BOOL flag) {
                
            }];
        }
        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
    
    
    //    [[HttpHelper sharedInstance] sendPost:@"api/user/pay/restore" parameters:paras success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
    //        DLog(@"payfinish===%@",responseObject.data);
    //        if (responseObject.code == 1) {
    //            [[UserInfoManager sharedManager] getUserInfoData];
    //        }
    //        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    //    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
    //        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    //    }];
}

@end
